package com.example.wx.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;






//    {
//            "env":"test2-4a89da",
//                "query": "db.collection(\"geo\").add({
//            data: [{
//            description: \"item1\",
//            due: new Date(\"2019-09-09\"),
//                    tags: [
//              \"cloud\",
//              \"database\"
//            ],
//            location: new db.Geo.Point(113, 23),
//                    done: false
//        },
//            {
//                description: \"item2\",
//                due: new Date(\"2019-09-09\"),
//                        tags: [
//              \"cloud\",
//              \"database\"
//            ],
//                location: new db.Geo.Point(113, 23),
//                        done: false
//            }
//          ]
//        })"
//    }




//删除
//    {
//        "env":"test2-4a89da",
//            "query": "db.collection(\"geo\").where({done:false}).remove()"
//    }

//请求数据示例
//    {
//        "env":"test2-4a89da",
//            "query": "db.collection(\"geo\").where({done:true}).limit(10).skip(1).get()"
//    }


//更新替换一条记录
//    {
//        "env":"test2-4a89da",
//            "query": "db.collection(\"geo\").doc(\"be62d9c4-43ec-4dc6-8ca1-30b206eeed24\").set({data: {
//        description: \"set\",
//        done: true
//        }})"
//    }



public class DataBaseUtil {
    private static final String SOURCE_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1a2b6bf6d51d6a60&secret=14c9e92c8db8e094f982d5b91a3d389d";

    private static final String SOURCE_URL_FUNC = "https://api.weixin.qq.com/tcb/invokecloudfunction?name=getUncheckedCase";

    //返回结果为json子串，request为要执行的数据库操作语句，类似与sql
    public static JSONObject action(String request){
        //获取到access_token，再创建一个用于查询的json（这里写了一个string类型的json数据），通过下面的api接口就可以获取到响应的数据，查询语句在json里写
        String result=httpRequest("https://api.weixin.qq.com/tcb/databasequery?access_token="+getAccess_Token(),"POST",request);
        //查询成功的话会返回这样的结果{"errcode":0,"errmsg":"ok","pager":{"Offset":0,"Limit":10,"Total":1},"data":["{\"_id\":\"id\",\"_openid\":\"openid\",\"date\":\"2020-06-04\",\"department\":\"1\",\"name\":\"1\",\"phone\":\"1\",\"radio\":\"2\"}"]}
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    public static JSONObject actionFunc(String request){
        //获取到access_token，再创建一个用于查询的json（这里写了一个string类型的json数据），通过下面的api接口就可以获取到响应的数据，查询语句在json里写
        String result=httpRequest("https://api.weixin.qq.com/tcb/invokecloudfunction?access_token="+getAccess_Token(),"POST",request);
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    //动态获取access_taken
    public static String getAccess_Token(){
        String response = HttpRequest.get(SOURCE_URL).body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        String access_token= (String) jsonObject.getString("access_token");
        return access_token;
    }

    //处理http请求  requestUrl为请求地址  requestMethod请求方式，值为"GET"或"POST"
    public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
        StringBuffer buffer=null;
        try{
            URL url=new URL(requestUrl);
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod(requestMethod);
            conn.connect();
            //往服务器端写内容 也就是发起http请求需要带的参数
            if(null!=outputStr){
                OutputStream os=conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is=conn.getInputStream();
            InputStreamReader isr=new InputStreamReader(is,"utf-8");
            BufferedReader br=new BufferedReader(isr);
            buffer=new StringBuffer();
            String line=null;
            while((line=br.readLine())!=null){
                buffer.append(line);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
